package com.party.admin.web.controller.mall;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.party.admin.biz.mall.MallOrderBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.input.mall.MallOrderQueryInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.logistics.WlExpress;
import com.party.core.model.mall.*;
import com.party.core.service.logistics.IWlExpressService;
import com.party.core.service.mall.IMallEvaluateService;
import com.party.core.service.mall.IMallOrderDetailService;
import com.party.core.service.mall.IMallStoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Administrator.
 * @Description: 商城订单
 * @Date:Created in 2017/9/4 0004 下午 15:03.
 */
@Controller
@RequestMapping("mall/order")
public class MallOrderController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IMallOrderDetailService mallOrderDetailService;
    @Autowired
    private MallOrderBizService mallOrderBizService;
    @Autowired
    private IMallEvaluateService mallEvaluateService;
    @Autowired
    private IWlExpressService wlExpressService;
    @Autowired
    private IMallStoreService mallStoreService;

    /**
     * 订单列表
     *
     * @param orderDetail
     * @param commonInput
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(MallOrderDetail orderDetail, CommonInput commonInput, Page page, MallOrderQueryInput orderQueryInput) {
        page.setLimit(10);
        ModelAndView mv = new ModelAndView("mall/order/orderList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        params.put("transactionId", orderQueryInput.getTransactionId());
        params.put("distributorName", orderQueryInput.getDistributorName());
        if(null == orderDetail.getOrderType()){
            orderDetail.setOrderType(1);
        }
        List<MallOrderOutputPay> orderList = mallOrderBizService.webListPage(orderDetail, orderQueryInput.getPayStatus(), params, page);
        mv.addObject("statusMap", MallOrderDetailStatus.convertMap());
        mv.addObject("orderList", orderList);
        mv.addObject("orderDetail", orderDetail);
        mv.addObject("input", commonInput);
        mv.addObject("page", page);
        mv.addObject("queryInput", orderQueryInput);
        return mv;
    }

    /**
     * 订单详情
     *
     * @param orderId 支付订单id
     * @return
     */

    @RequestMapping("getDetail")
    public ModelAndView getDetail(String orderId) {
        ModelAndView mv = new ModelAndView("/mall/order/orderDetail");
        Map<String, Object> result = mallOrderBizService.getDetail(orderId);
        mv.addAllObjects(result);
        return mv;
    }

    /**
     * 选择订单发货
     *
     * @param orderId 支付订单id
     * @return
     */
    @ResponseBody
    @RequestMapping("selectOrderDetail")
    public AjaxResult selectOrderDetail(String orderId) {
        MallStore mallStore = mallStoreService.getUnique();
        Map<String, Object> result = Maps.newHashMap();
        MallOrderDetail odPartner = mallOrderDetailService.getUniqueByOrderId(orderId);
        result.put("odPartner", odPartner);

        Set<Integer> status = Sets.newHashSet();
        status.add(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode());
        status.add(MallOrderDetailStatus.STATUS_HAVE_SHIPMENT.getCode());
        status.add(MallOrderDetailStatus.STATUS_COMPLETE.getCode());
        status.add(MallOrderDetailStatus.STATUS_REFUND_REJECT.getCode());
        List<MallOrderOutputParent> outputParents = mallOrderDetailService.listWithLogistics(orderId, status);
        int length = 0;
        for (MallOrderOutputParent outputParent : outputParents) {
            for (MallOrderOutputChild outputChild : outputParent.getChildrens()) {
                if (outputChild.getStatus().equals(MallOrderDetailStatus.STATUS_NOT_SHIPMENT.getCode())) {
                    length++;
                }
            }
            mallOrderBizService.transfromStoreName(mallStore, outputParent);
        }
        result.put("waitShipment", length);
        result.put("outputParents", outputParents);

        List<WlExpress> mallExpresses = wlExpressService.getAllExpress();
        result.put("couriers", mallExpresses);
        return AjaxResult.success(result);
    }

    /**
     * 退款审核
     *
     * @param orderDetailId 子订单id
     * @param status        状态 1：同意 2：拒绝
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkRefund", method = RequestMethod.POST)
    public AjaxResult checkRefund(String orderDetailId, Integer status) {
        if (StringUtils.isEmpty(orderDetailId)) {
            return AjaxResult.error("id不能为空");
        }
        if (status == null) {
            return AjaxResult.error("状态不能为空");
        }

        try {
            mallOrderBizService.checkRefund(orderDetailId, status);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("退款审核异常", e);
            return AjaxResult.error("退款审核异常");
        }
        return AjaxResult.success();
    }

    /**
     * 评价列表
     *
     * @param evaluate
     * @param input
     * @param page
     * @return
     */
    @RequestMapping("evaluateList")
    public ModelAndView evaluateList(MallEvaluate evaluate, CommonInput input, Page page, String type) {
        ModelAndView mv = new ModelAndView("/mall/order/evaluateList");
        Map<String, Object> params = CommonInput.appendParams(input);
        if (StringUtils.isNotEmpty(type)) {
            if (type.equals("2")) { // 好评
                params.put("level", MallEvaluate.LEVEL_GOOD);
            } else if (type.equals("3")) { // 中评
                params.put("level", MallEvaluate.LEVEL_ZHONG);
            } else if (type.equals("4")) { // 差评
                params.put("level", MallEvaluate.LEVEL_BAD);
            } else if (type.equals("5")) { // 有图
                params.put("hasPic", true);
            }
        }

        List<MallEvaluateListOutput> outputs = mallEvaluateService.webListPage(evaluate, params, page);
        mv.addObject("evaluateList", outputs);
        mv.addObject("evaluate", evaluate);
        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("type", type);
        return mv;
    }

    /**
     * 删除评价
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteEvaluate")
    public AjaxResult deleteEvaluate(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        mallEvaluateService.delete(id);
        return AjaxResult.success();
    }

    /**
     * 更新卖家备注
     *
     * @param orderId       支付订单id
     * @param sellerRemarks 卖家备注
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateSellerRemarks", method = RequestMethod.POST)
    public AjaxResult updateSellerRemarks(String orderId, String sellerRemarks) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error("主订单id不能为空");
        }
        List<MallOrderDetail> parents = mallOrderDetailService.findParentByOrderId(orderId);
        for (MallOrderDetail parent : parents) {
            parent.setSellerRemarks(sellerRemarks);
            mallOrderDetailService.update(parent);
        }
        return AjaxResult.success();
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "receiveShipment", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult receiveShipment(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            return AjaxResult.error("订单id不能为空");
        }
        try {
            mallOrderBizService.receiveShipment(orderId);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("确认收货异常", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("确认收货异常", e);
            return AjaxResult.error("确认收货异常");
        }
    }
}
